package com.ml.util;

import java.sql.*;
import java.util.Properties;

/**
 * 读取Access数据的工具类
 * @Author ZZY
 * */
public class ReadAccess {
    public static String driver =  UtilProperties.getConfig("jdbc.driver");
    public static String url =  UtilProperties.getConfig("jdbc.url");
    public static String username =  UtilProperties.getConfig("jdbc.username");
    public static String password =  UtilProperties.getConfig("jdbc.password");

    /**
     * 打开access数据库连接
     */
    public  Connection openConnect(){
        Connection con = null;
        ResultSet rst = null;
        Statement sta = null;
        try {
            Class.forName(driver);
            Properties pro = new Properties();//此方案解决中文乱码
            pro.setProperty("charSet","GB2312");
            pro.put( "charSet", "gbk" );
            pro.put( "user", username );
            pro.put( "password", password );
            con = DriverManager . getConnection( url, pro );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  con;
    }
    /**
     * 关闭access数据库连接
     */
    public  void closeConnect(Connection conn,Statement sta,PreparedStatement ps,ResultSet rst){
        try {
            if(rst!=null){
                rst.close();
            }
            if(sta!=null){
                sta.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 这个是查询的示例
     * @param sql
     */
    public  void executeQuery(String sql ){
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                String title = rs.getString("title");
                System.out.println(rs.getString("name")+"--"+title);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            this.closeConnect(conn,null,ps,rs);
        }
    }


    /**
     * 只适合 增加 		删除	 	修改	操作
     * 执行SQL语句的方法
     */
    public void execute(String sql,Object param[]) {
        Connection conn=null;
        PreparedStatement ps=null;
        conn=this.openConnect();
        try {
            ps=conn.prepareStatement(sql);
            if(param!=null && param.length!=0){
                for(int i=0;i<param.length;i++){
                    //把每一个对象param放入数组中
                    ps.setObject((i+1), param[i]);
                }
            }
            ps.execute();//执行SQL语句
            this.closeConnect(conn, null, ps, null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
